package com.example.demo.config.builder;

import java.util.EnumSet;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;

import com.example.demo.config.enum_.FormEvents;
import com.example.demo.config.enum_.FormStates;

import lombok.extern.slf4j.Slf4j;

/**
 * 构建表单状态机
 */
@Component
@Slf4j
public class FormStateMachineBuilder {
	public static final String MACHINEID="formMachine";
	@Autowired
	private BeanFactory beanFactory;

	/**
	 * 构建状态机
	 * 
	 * @return
	 * @throws Exception
	 */
	public StateMachine<FormStates, FormEvents> build() throws Exception {
		StateMachineBuilder.Builder<FormStates, FormEvents> builder = StateMachineBuilder.builder();
		log.info("构建表单状态机");
		builder.configureConfiguration().withConfiguration().machineId(MACHINEID).beanFactory(beanFactory);
		
		builder.configureStates()
			.withStates().initial(FormStates.BLANK_FORM)
			.states(EnumSet.allOf(FormStates.class));
		
		
		builder.configureTransitions()
			.withExternal()
				.source(FormStates.BLANK_FORM).target(FormStates.FULL_FORM)
				.event(FormEvents.WRITE)
				.and()
			.withExternal()
				.source(FormStates.FULL_FORM).target(FormStates.CONFIRM_FORM)
				.event(FormEvents.CONFIRM)
				.and()
			.withExternal()
				.source(FormStates.CONFIRM_FORM).target(FormStates.SUCCESS_FORM)
				.event(FormEvents.SUBMIT);
		return builder.build();
	}
}
